package cn.zero.exception;

import cn.zero.enums.GlobalExceptionCode;
import cn.zero.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult globalException(Exception e){
        log.error(e.getMessage());
        e.printStackTrace();
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalException(GlobalCustomException e){
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult globalException(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stb = new StringBuffer();

        allErrors.stream().forEach(obj ->{
            stb.append("--").append(obj.getDefaultMessage()).append("--");
        });

        return JSONResult.error(stb.toString(),"1000");
    }
}
